﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// Tmall login command handler.
    /// </summary>
    public sealed class TmallLoginCommandHandler:BaseCommandHandler,IRequestHandler<TmallLoginCommand,BaseResult<string>>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.Application.Commands.TmallLoginCommandHandler"/> class.
        /// </summary>
        /// <param name="netICService">Net ICS ervice.</param>
        /// <param name="httpClientFactory">Http client factory.</param>
        /// <param name="optionsSnapshot">Options snapshot.</param>
        public TmallLoginCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> optionsSnapshot) 
        :base(netICService,httpClientFactory,optionsSnapshot)
        {
        }

        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<BaseResult<string>> Handle(TmallLoginCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var url = "TPP/v1/Account/CheckLoginByPwd";
            var result = await PostAsync(url, JsonConvert.SerializeObject(new {request.UserName,request.Password })).ConfigureAwait(false);
            var rsp = JsonConvert.DeserializeObject<JObject>(result);
            if (rsp["resultNo"].ToString() != "00000000")
            {
                return new BaseResult<string>("", 9999, rsp["resultRemark"].ToString());
            }
            var token = JsonConvert.DeserializeObject<JObject>( rsp["data"].ToString());
            return new BaseResult<string>(token["token"].ToString(), 0, "");
        }
    }
}
